package com.ksyun.campus.dataserver.services;

import com.google.gson.Gson;
import com.ksyun.campus.dataserver.domain.ApiResponse;

import com.ksyun.campus.dataserver.domain.dto.ReadDTO;
import com.ksyun.campus.dataserver.domain.dto.WriteContentDTO;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Service
@Slf4j
public class DataService {
    @Autowired
    CuratorFramework curatorFramework;

    @Autowired
    Gson gson;

    @Autowired
    RestTemplate restTemplate;

    public ApiResponse write(WriteContentDTO writeContentDTO) {
        //在creat阶段已经将三个副本选好了
        String path = writeContentDTO.getPath();
        File file = new File(path);
        //目录不存在则创建目录
        File parentDir = file.getParentFile();
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }
        try (FileOutputStream fos = new FileOutputStream(path)) {
            int length = writeContentDTO.getLength();
            int offset = writeContentDTO.getOffset();
            byte[] bytes = writeContentDTO.getBytes();
            fos.write(bytes, offset, length - offset);
            return new ApiResponse(200, "OK", null);
        } catch (Exception e) {
            log.error("写入文件失败：{}", e.getMessage());
            return new ApiResponse(500, "文件在dateServer写入失败:"+e.getMessage(), null);
        }
    }

    public byte[] read(ReadDTO readDTO){
        try {
            FileInputStream fis = new FileInputStream(readDTO.getPath());
            fis.skip(readDTO.getOffset()); // 设置偏移量
            byte[] buffer = new byte[readDTO.getLength()];
            int bytesRead = fis.read(buffer); // 读取指定大小的内容
            fis.close();

            if (bytesRead == -1) {
                return null;
            }

            return Arrays.copyOf(buffer, bytesRead);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public ApiResponse deleteFile(String path) {
        // 删除传来的path文件
        File file = new File(path);
        if (file.exists()) {
            if (file.delete()) {
                // 文件删除成功
                return new ApiResponse(200, "File deleted successfully",null);
            } else {
                // 文件删除失败
                return new ApiResponse(500, "Failed to delete file",null);
            }
        } else {
            // 文件不存在
            return new ApiResponse(404, "File not found",null);
        }
    }
}
